﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZHJ.PerfectOA.DALFactory;

namespace ZHJ.PerfectOA.BLL
{
    public abstract class BaseService<T> where T : class,new()
    {
        /// <summary>
        /// 只读属性 ，获得DBSession对象
        /// </summary>
        public IDAL.IDBSession GetDbSession
        {
            get
            {
                return DBSessionFactory.GetCurrentDbSession();
            }
        }

        /// <summary>
        /// 相当于简单三层中的DAL对象
        /// </summary>
        public IDAL.IBaseDal<T> CurrentDal { set; get; }

        /// <summary>
        /// 定义抽象方法 给子类重写，每个子类传一个具体对象过来，赋值给CurrentDal
        /// </summary>
        public abstract void SetCurrentDal();

        /// <summary>
        /// 静态构造函数，在方法调用的时候 执行SetCurrentDal方法
        /// </summary>
        public BaseService()
        {
            SetCurrentDal();
        }
        /// <summary>
        /// 加载数据方法
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            return this.CurrentDal.LoadEntities(whereLambda);
        }
        /// <summary>
        /// 分页加载数据方法
        /// </summary>
        /// <typeparam name="s"></typeparam>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <param name="whereLambda"></param>
        /// <param name="orderbyLambda"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc)
        {
            return this.CurrentDal.LoadPageEntities<s>(pageIndex, pageSize, out totalCount, whereLambda, orderbyLambda, isAsc);
        }
        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool DeleteEntity(T entity)
        {
            this.CurrentDal.DeleteEntity(entity);
            return this.GetDbSession.SaveChanges();
        }
        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool EditEntity(T entity)
        {
            this.CurrentDal.EditEntity(entity);
            return this.GetDbSession.SaveChanges();
        }
        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T AddEntity(T entity)
        {
            this.CurrentDal.AddEntity(entity);
            this.GetDbSession.SaveChanges();
            return entity;
        }
    }
}
